package com.rt.easyjava.common.utils.random;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rt.easyjava.common.utils.others.DateTool;

import java.util.Random;

public class RandomUtils {

    public static void main(String[] args) {
        // 使用默认 rule
        System.out.println("默认 rule: "+getRandom(RandomRules.rule1, 100000, 100100));

        // 使用自定义 rule, 没有的时间段，使用默认随机范围
        JSONArray myRule = new JSONArray();
        RandomRules.addTimeJsonObject(myRule, 7, 20,30);
        RandomRules.addTimeJsonObject(myRule, 8, 100,150);
        RandomRules.addTimeJsonObject(myRule, 9, 500,550);
        RandomRules.addTimeJsonObject(myRule, 10, 600,660);
        RandomRules.addTimeJsonObject(myRule, 11, 700,770);
        RandomRules.addTimeJsonObject(myRule, 12, 800,880);
        RandomRules.addTimeJsonObject(myRule, 13, 800,880);
        RandomRules.addTimeJsonObject(myRule, 14, 800,880);
        RandomRules.addTimeJsonObject(myRule, 15, 800,900);
        RandomRules.addTimeJsonObject(myRule, 16, 900,990);
        System.out.println("自定义 rule: "+getRandom(myRule, 80, 99));

    }


    public static int getRandom(JSONArray rule, int defaultMin, int defaultMax) {
        if (rule==null || rule.isEmpty()) {
            return getRandomSimple(defaultMin, defaultMax);
        }
        int hour = Integer.parseInt(DateTool.getCurrentDateStr1("HH"));
        for (int i=0;i<rule.size();i++) {
            JSONObject timeJo = rule.getJSONObject(i);
            int time = timeJo.getInteger("time");
            int min = timeJo.getInteger("min");
            int max = timeJo.getInteger("max");
            if (hour == time) {
                return getRandomSimple(min, max);
            }
        }
        return getRandomSimple(defaultMin, defaultMax);
    }

    public static int getRandomSimple(int min, int max) {
        return new Random().nextInt(max + 1 - min) + min;
    }
}
